import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'

declare var $: any
declare var echarts: any
declare var Viewer: any
@Component({
  selector: 'sa-repaire-detail',
  templateUrl: './repaire-detail.component.html',
  styleUrls: ['./repaire-detail.component.css']
})
export class RepaireDetailComponent implements OnInit {
  factoryvalidatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      companyName: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择公司名称'
          }
        }
      },
      selfTimeInputId: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择时间段'
          }
        }
      }
    }
  }
  tableData: any = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  searchKey: string = '' //搜索keyword
  btnData: any = []
  resourceAdd: boolean = false
  resourceEdit: boolean = false
  resourceDeleteBatch: boolean = false
  faultTypeName: string = '' //查询故障类型参数
  isPush: string = '' //是否推送
  repairedStatus: string = '' //查询故障状态参数
  selectedCompanyName: string = '' //查询公司参数
  selectedCompanyId: string = '' //查询公司参数
  deviceId: string = '' //查询设备参数
  userList: any = [] //用户数据List
  userName: string = '' //查询用户参数
  userId: string = '' //查询用户id参数
  startTime = '' //查询开始时间参数
  endTime = '' //查询结束时间参数
  dateType: string = '1' //时间类型
  sortType: string = '2' //时间类型
  useTypeL1: string = '' //车辆分类一级
  useTypeL2: string = '' //车辆分类二级
  pType: any = '' // 现象查询条件
  type: any = '' // 内容查询条件

  faultTypeArr: any = [
    {
      type: 1,
      text: '主机故障'
    },
    {
      type: 2,
      text: '传感器故障'
    },
    {
      type: 3,
      text: 'GPS故障'
    }
  ]

  modal: any = {
    //图片弹窗
    picture: '',
    active: '', //激活的图片
    activeNum: null //激活的图片下标
  }
  inputCompanyTreeCarData: any = {} //车辆运行状态模块跳转该页面传递过来的参数
  carDeatailUseList: any = carTypeListObj.carDeatailUseList
  jumpData: any // 跳转页面接收到的数据
  deviceRepairedId: any = '' // 从订单中跳过来带的维修记录id

  // 大类的数组 现象的数组
  pTypeList: any = ['离线问题', 'GPS问题', '传感器问题','甩挂问题']
  // 小类的数组 内容的数组
  typeList: any = [
    '更换主机',
    '电源维修',
    '更换线材',
    '挪动天线位置',
    '更换天线',
    'V4换V7',
    '更换传感器',
    '重新焊接',
    '离线其他',
    'GPS其他',
    '传感器其他',
    '无维修'
  ]
  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      if (common.getCookie('repaireDetail')) {
        this.jumpData = JSON.parse(common.getCookie('repaireDetail'))
        common.clearCookie('repaireDetail')
      }
    })
  }
  editCheck: boolean = false
  //权限按钮
  initBtn() {
    this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_device:repaire:detail')))
    if (!this.btnData) {
      return
    }
    for (let item of this.btnData) {
      if (item.sourceKey === 'repaireDetail:editCheck' && item.parentId) {
        this.editCheck = true
      }
    }
  }
  ngOnInit() {
    // 初始化用户
    var that = this
    this.initBtn()
    // this.initAllUser().then(() => {
    // 	this.selectUserName();
    // });
    if (this.jumpData) {
      this.deviceRepairedId = this.jumpData.id
      // this.searchKey = this.jumpData.deviceId
      this.deviceId = this.jumpData.deviceId

      this.initDate(false).then(() => {
        // 只初始化时间选择框  不选择时间
        this.load()
      })
    } else {
      this.initDate(true).then(() => {
        this.load()
      })
    }
  }
  ngOnDestroy() {
    document.onclick = null
  }

  //初始化时间  initDate表示是否初始化前31天的时间
  initDate(initDate) {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
        System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
          $('#datetimepicker3')
            .datetimepicker({
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeMmss(date)
              that.startTime = time
              $('#datetimepicker4').datetimepicker('setStartDate', time)
            })
          $('#datetimepicker4')
            .datetimepicker({
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeMmss(date)
              that.endTime = time
              $('#datetimepicker3').datetimepicker('setEndDate', time)
            })
          if (initDate) {
            var date = new Date()
            let time1 = common.getTimeMmss(date)
            $('#datetimepicker4').val(time1) //当前时间
            that.endTime = time1
            date.setDate(date.getDate() - 31) //设置前31天
            let time2 = common.getTimeMmss(date)
            $('#datetimepicker3').val(time2)
            that.startTime = time2
          }
          resolve()
        })
      })
    })
  }
  //删除所选时间
  del_date() {
    this.startTime = ''
    this.endTime = ''
    $('#datetimepicker3').val('').change()
    $('#datetimepicker4').val('').change()
    $('#datetimepicker4').datetimepicker('setStartDate', null)
    $('#datetimepicker3').datetimepicker('setEndDate', null)
  }
  /**
   * 用户类型的选择
   */
  //擦除用户所选值
  delUserName() {
    this.userName = ''
    this.userId = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#userNameSelect2').val('')
    $('#select2-userNameSelect2-container').empty()
    $('#select2-userNameSelect2-container').attr('title', '')
    $('#select2-userNameSelect2-container').prepend(str)
  }
  //拉取
  initAllUser() {
    var that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('user/getAllUserList.html', null).subscribe(data => {
        if (data.success) {
          var userList = data.data
          var selectdata = []
          for (var i = 0; i < userList.length; i++) {
            var obj = {
              id: userList[i].id,
              text: userList[i].name
            }
            selectdata[i] = obj
          }
        }
        that.userList = selectdata
        resolve()
      })
    })
  }
  //初始化select2 选项
  selectUserName() {
    var that = this
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        $('#userNameSelect2')
          .select2({
            language: 'zh-CN',
            placeholder: '请选择',
            allowClear: true,
            data: this.userList, //为Select添加数据
            templateResult: this.formatRepo
          })
          .on('select2:select', function (e) {
            var data = e.params.data
            that.userName = data.text
            that.userId = data.id
          })
      })
    })
  }
  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text
    }
    var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>')
    return $state
  }

  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.searchKey = common.stringTrim(this.searchKey)
    // 点击搜索的时候清除维修订单id  不然条件搜索都是这个id
    this.deviceRepairedId = ''
    this.load()
  }
  // 大的类进行切换
  btnClick(type) {
    this.pType = type
    this.curPage = 1
    this.load()
  }
  //初始化加载list数据  TODO
  load() {
    var that = this
    if (this.jumpData) {
      setTimeout(() => {
        var str = $("<span class='select2-selection__rendered'>" + that.jumpData.carNumber + '</span>')
        $('#carNumberSelect2').val(that.jumpData.carNumber)
        $('#select2-carNumberSelect2-container').empty()
        $('#select2-carNumberSelect2-container').attr('title', '')
        $('#select2-carNumberSelect2-container').prepend(str)
        // 初始化搜索条件后需要清空数据，不然会重复被旧数据覆盖
        this.jumpData = ''
      }, 100)
    }

    this.startTime = $('#datetimepicker3').val()
    this.endTime = $('#datetimepicker4').val()
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        searchKey: this.searchKey.trim(),
        companyId: this.selectedCompanyId,
        startDate: this.startTime,
        endDate: this.endTime,
        userName: this.userName,
        deviceId: this.deviceId,
        pType: this.pType,
        type: this.type,
        deviceRepairedId: this.deviceRepairedId
        // useTypeL2: this.useTypeL2,
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('deviceRepairedV2/deviceRepairedDetailList.html', reqdata).subscribe(result => {
      this.tableData = result.exhibitDatas || []
      for (let item of this.tableData) {
        item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2)
        // 将维修内容数组进行拼接
        let str = ''
        for (let idx = 0; idx < item.repairContent.length; idx++) {
          const element = item.repairContent[idx]
          if (idx != item.repairContent.length - 1) {
            str += element + ' , '
          } else {
            str += element
          }
        }
        item.repairContentStr = str
      }

      this.totalCount = result.recordCount
    })
  }

  // 车辆分类编码转化
  getUseTypeNameL2(key) {
    if (key) {
      return this.carDeatailUseList[key]
    } else {
      return ''
    }
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  //公司选中回调
  companySelected(data) {
    this.selectedCompanyId = data.companyId
    this.selectedCompanyName = data.companyName
    this.deviceId = data.deviceId
    this.useTypeL2 = data.useTypeL2
    this.useTypeL1 = data.useTypeL1
  }

  /**
   * 图片查看的功能
   */
  imageType: any
  imagesInfo: any = [] //图片展示
  isViewer: boolean = false //默认隐藏
  afterImageInfo: any = []
  beforeImageInfo: any = []
  //显示图片组件
  viewer: any = ''
  //查看照片
  open_img(row, val) {
    this.afterImageInfo = []
    this.beforeImageInfo = []
    //1主机 2采集器 3传感器 4线材 5GPS 6其他
    // if (type == "after") {
    // 返回的维修后图片列表数据
    // this.imageType = "维修后";
    var imageinfoObj1 = {
      imageUrl: row.afterImageInfo,
      name: this.pTypeList[row.pType * 1 - 1]
    }
    this.afterImageInfo.push(imageinfoObj1)
    // this.imagesInfo = JSON.parse(JSON.stringify(row.afterImageInfo));
    // }
    // if (type == "before") {
    // 返回的维修前图片列表数据
    // this.imageType = "维修前";
    var imageinfoObj2 = {
      imageUrl: row.beforeImageInfo,
      name: this.pTypeList[row.pType * 1 - 1]
    }
    this.beforeImageInfo.push(imageinfoObj2)
    // this.imagesInfo = JSON.parse(JSON.stringify(row.beforeImageInfo));
    // }
    // this.imagesInfo=['https://goss.veer.com/creative/vcg/veer/800water/veer-134167863.jpg','https://goss.veer.com/creative/vcg/veer/800water/veer-134167863.jpg','https://goss.veer.com/creative/vcg/veer/800water/veer-134167863.jpg']
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
    val.show()
    // if (row.paths.length > 0) {
    // 	this.modal.active = row.paths[0];
    // 	this.modal.activeNum = 0;
    // 	this.modal.picture = row.paths;
    // }
  }
  //图片放大
  bigimg() {
    // modal.show();
    if (this.isViewer && $('.viewer-container').length > 0) {
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showImg()
          })
        })
      })
    } else {
      this.showImg()
    }
  }
  showImg() {
    var that = this
    var imgList = $('.imagesInfo')[0]
    this.viewer = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    that.isViewer = true
  }
  //图片hover事件
  switch_img(index) {
    this.modal.activeNum = index
    this.modal.active = this.modal.picture[index]
  }
  //pre
  change_img_left() {
    if (this.modal.activeNum) {
      this.modal.activeNum--
      this.modal.active = this.modal.picture[this.modal.activeNum]
    }
  }
  //next
  change_img_right(e) {
    if (this.modal.activeNum < this.modal.picture.length - 1) {
      this.modal.activeNum++
      this.modal.active = this.modal.picture[this.modal.activeNum]
    }
  }
  //关闭图片弹窗
  imgClose(val) {
    val.hide()
  }
  // 新增删除功能 2020-12-15
  deleteRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('deviceRepairedV2/delDeviceRepairedDetailV2.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }

  /**
   * 编辑
   */
  repairContentStr: any = ''
  repairContent: any = []
  repairContentId: any = ''
  repairedPType: string = '' // 故障现象
  repairedType: string = '' // 故障类型
  faultPhenomenon: string = '' // 故障现象详细
  faultPhenomenonList: any = [] //故障现象详细数据
  repairedPTypeChange() {
    this.faultPhenomenonList = []
    this.faultPhenomenon = ''
    switch (this.repairedPType) {
      case '1':
        this.faultPhenomenonList = [
          {
            label: '请选择',
            value: ''
          },
          {
            label: '离线',
            value: '离线'
          },
          {
            label: '在线',
            value: '在线'
          }
        ]
        break
      case '2':
        this.faultPhenomenonList = [
          {
            label: '请选择',
            value: ''
          },
          {
            label: '正常',
            value: '正常'
          },
          {
            label: '偶尔丢失',
            value: '偶尔丢失'
          },
          {
            label: '大段丢失',
            value: '大段丢失'
          },
          {
            label: '停车速度平直',
            value: '停车速度平直'
          },
          {
            label: '无GPS',
            value: '无GPS'
          }
        ]
        break
      case '3':
        this.faultPhenomenonList = [
          {
            label: '请选择',
            value: ''
          },
          {
            label: '正常',
            value: '正常'
          },
          {
            label: '正负52万',
            value: '正负52万'
          },
          {
            label: '经常52万',
            value: '经常52万'
          },
          {
            label: '偶尔52万',
            value: '偶尔52万'
          },
          {
            label: '乱跳',
            value: '乱跳'
          },
          {
            label: '形变小',
            value: '形变小'
          },
          {
            label: '平直',
            value: '平直'
          },
          {
            label: '方向反',
            value: '方向反'
          },
          {
            label: '全部平直',
            value: '全部平直'
          }
        ]
        break
      case '4':
          this.faultPhenomenonList = [
            {
              label: '请选择',
              value: ''
            },
            {
              label: '无故障',
              value: '无故障'
            }
            
          ]
          break
    }
  }
  editRow(row, modal) {
    this.repairContentId = row.id
    this.repairContent = JSON.parse(JSON.stringify(row.repairContent))
    this.repairedPType = row.pType + ''
    this.repairedType = row.type + ''
    this.repairedPTypeChange()
    this.faultPhenomenon = row.faultPhenomenon == '离线问题' ? '离线' : row.faultPhenomenon
    modal.show()
  }
  editClose(modal) {
    modal.hide()
  }
  addNum(index) {
    if (this.repairContent[index]) {
      var content = ''
      this.repairContent.push(content)
    }
  }
  // 数量减
  reduceNum(index) {
    this.repairContent.splice(index, 1)
  }
  contentChange(value, index) {
    this.repairContent[index] = value
  }
  editSubmit(modal) {
    if (this.repairContent.length < 1) {
      this.jsonApiService.message('必须要有一条维修内容')
      return
    }
    if (!this.repairedPType) {
      this.jsonApiService.message('请选择故障现象')
      return
    }
    if (!this.faultPhenomenon) {
      this.jsonApiService.message('请选择故障现象详情')
      return
    }
    if (!this.repairedType) {
      this.jsonApiService.message('请选择故障类型')
      return
    }
    // let repairContentArr = []
    // for (var i = 0; i < this.repairContent.length; i++) {
    //   if (this.repairContent[i]) {
    //     repairContentArr.push(this.repairContent[i].replace(/\s+/g, ''))
    //   }
    // }
    let reqdata = {
      id: this.repairContentId,
      repairContentStr: JSON.stringify(this.repairContent),
      pType: this.repairedPType,
      type: this.repairedType,
      faultPhenomenon: this.faultPhenomenon
    }
    this.jsonApiService.http_obj('deviceRepairedV2/editDeviceRepairedDetailV2.html', reqdata).subscribe(data => {
      if (data.success) {
        modal.hide()
        this.load()
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }

  // 编辑日志
  editLogTableData: any = []
  editLogRow(row, modal) {
    let param = 'deviceRepairedDetailId=' + row.id
    this.jsonApiService
      .http2('deviceRepairedV2/getDeviceRepairedDetailChangeLogListByDetailId.html', param)
      .subscribe(result => {
        this.editLogTableData = result.data
        modal.show()
      })
  }

  cancelEditLogModalModal(modal) {
    this.editLogTableData = []
    modal.hide()
  }
}
